<?php
/**
 * 分页类
 */
namespace Lib\Core;

class Pager extends \home {

    /**
     * 每页条数.
     *
     * @var integer
     */
    public $pageSize = 20;

    /**
     * 当前页.
     *
     * @var integer
     */
    public $currentPage = 1;

    /**
     * 如果为真当前页数大于最大页数会设置当前页等于最大页
     * @var bool
     */
    public $limitMaximumPage = false;

    /**
     * 总共多少业.
     *
     * @var
     */
    public $pageCount;

    /**
     * 总共多少条.
     *
     * @var int
     */
    public $count = 0;

    /**
     * 偏移量.
     *
     * @var int | null
     */
    public $offset;

    /**
     * url参数.
     *
     * @var array
     */
    public $parameters = array();

    /**
     * Uri.
     *
     * @var string
     */
    public $uri;

    /**
     * js分页方法名称.
     *
     * @var string
     */
    public $pageName;

    public $scriptFunc;

    /**
     * @param $pager
     * @return Pager
     */
    public static function getMe($pager) {
        $p = new Pager();
        foreach ($pager as $k => $v) {
            $p->$k = $v;
        }
        return $p;
    }

    public function getRemotePager() {
        $p = array();
        $p['Limit'] = $this->pageSize;
        if ($this->offset !== null) {
            $p['Offset'] = $this->offset;
        } else {
            $this->currentPage = $this->currentPage <= 0 ? 1 : $this->currentPage;
            $p['Offset'] = ($this->currentPage - 1) * $this->pageSize;
        }
        return $p;
    }

    public function setRemoteResult($p) {
        $this->count = $p['Count'];
        $this->pageCount = ceil($p['Count'] / $p['Limit']);
    }

    public function __construct($parameters = array(), $pageName = 'page') {
        if (!$parameters) {
            $parameters = $_GET;
            if (isset($parameters['_rp_'])) {
                unset($parameters['_rp_']);
            }
            if (isset($parameters['page'])) {
                unset($parameters['page']);
            }
        }
        $this->pageName = $pageName;
        $this->parameters = $parameters;
        if (empty($_SERVER)) {
            return;
        }
        if (!isset($_SERVER['REQUEST_URI'])) {
            return;
        }
        $uri = $_SERVER['REQUEST_URI'];
        $n = strpos($uri, '?');
        if ($n) {
            $uri = substr($uri, 0, $n);
        }
        if ($this->parameters) {
            $this->uri = $uri . '?';
            foreach ($this->parameters as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $val) {
                        $this->uri .= $k . '[]=' . htmlspecialchars($val) . '&';
                    }
                } else {
                    $this->uri .= $k . '=' . htmlspecialchars($v) . '&';
                }

            }
            $this->uri = trim($this->uri, '&');
        }
        if (strpos($this->uri, '?')) {
            $this->uri .= '&';
        } else {
            $this->uri .= '?';
        }
    }

}